﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace IInject.Registration
{
    public class KeyedEnumerableContextRegistry : RegistryBase<List<Tuple<string, IEnumerable<RegistryContext>>>>
    {
        public KeyedEnumerableContextRegistry(IContainer container) : base(container)
        {
        }

        public override bool Contains(Type type, string key)
        {
            return key != null && Contains(type) && Get(type).Any(t => t.Item1 == key);
        }

        public override RegistryContext Get(Type type, string key)
        {
            return null;
        }

        public override IEnumerable<RegistryContext> GetAll(Type type, string key)
        {
            if (key != null)
            {
                return Get(type).Single(r => r.Item1 == key).Item2;
            }

            return null;
        }

        public override bool Register(Type from, RegistryContext context)
        {
            return false;
        }

        public override bool Register(Type from, string key, IEnumerable<RegistryContext> contexts)
        {
            if (key != null && contexts.Count() > 0)
            {
                if (!Contains(from))
                {
                    Add(from, new List<Tuple<string, IEnumerable<RegistryContext>>>());
                }

                var list = base[from];

                if (list.Any(t => t.Item1 == key))
                {
                    throw new RegistrationException(from, key);
                }

                list.Add(Tuple.Create(key, contexts));
                return true;
            }

            return false;
        }
    }
}
